<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 搜索和操作区域 -->
      <div class="filter-container">
        <el-input
          v-model="searchFileNum"
          placeholder="请输入档案编号"
          style="width: 150px"
          class="filter-item"
          clearable
          @clear="getList"
        />
        <el-input
          v-model="searchBorrower"
          placeholder="请输入借阅人"
          style="width: 150px"
          class="filter-item"
          clearable
          @clear="getList"
        />
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">申请借阅</el-button>
      </div>

      <!-- 表格部分 -->
      <el-table v-loading="loading" :data="tableData" border style="width: 100%">
        <el-table-column prop="recordId" label="记录ID" width="80" align="center" />
        <el-table-column prop="fileNum" label="档案编号" width="120" align="center" />
        <el-table-column prop="borrowerName" label="借阅人" width="100" />
        <el-table-column prop="borrowerDepartment" label="借阅部门" width="100" />
        <el-table-column prop="borrowReason" label="借阅原因" min-width="150" show-overflow-tooltip />
        <el-table-column prop="borrowDate" label="借阅日期" width="160" align="center">
          <template slot-scope="scope">
            {{ scope.row.borrowDate ? scope.row.borrowDate.substring(0, 16) : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="expectedReturnDate" label="预计归还日期" width="160" align="center">
          <template slot-scope="scope">
            {{ scope.row.expectedReturnDate ? scope.row.expectedReturnDate.substring(0, 16) : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template slot-scope="{row}">
            <div class="operation-buttons">
              <el-select
                v-model="row.status"
                size="mini"
                style="width: 100px; margin-right: 10px"
                @change="(value) => handleStatusChange(row.recordId, value)"
              >
                <el-option label="待审批" value="待审批" />
                <el-option label="已批准" value="已批准" />
                <el-option label="已拒绝" value="已拒绝" />
                <el-option label="已归还" value="已归还" />
              </el-select>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(row.recordId)"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog title="申请借阅" :visible.sync="dialogVisible" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="档案编号" prop="fileNum">
          <el-input v-model="form.fileNum" placeholder="请输入档案编号" />
        </el-form-item>
        <el-form-item label="借阅人姓名" prop="borrowerName">
          <el-input v-model="form.borrowerName" placeholder="请输入借阅人姓名" />
        </el-form-item>
        <el-form-item label="借阅人部门" prop="borrowerDepartment">
          <el-input v-model="form.borrowerDepartment" placeholder="请输入借阅人部门" />
        </el-form-item>
        <el-form-item label="联系电话" prop="borrowerPhone">
          <el-input v-model="form.borrowerPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="借阅原因" prop="borrowReason">
          <el-input
            type="textarea"
            v-model="form.borrowReason"
            :rows="3"
            placeholder="请输入借阅原因"
          />
        </el-form-item>
        <el-form-item label="预计归还日期" prop="expectedReturnDate">
          <el-date-picker
            v-model="form.expectedReturnDate"
            type="datetime"
            placeholder="选择预计归还日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'FileBorrow',
  data() {
    return {
      loading: false,
      dialogVisible: false,
      tableData: [],
      form: {
        fileNum: '',
        borrowerName: '',
        borrowerDepartment: '',
        borrowerPhone: '',
        borrowReason: '',
        expectedReturnDate: ''
      },
      rules: {
        fileNum: [
          { required: true, message: '请输入档案编号', trigger: 'blur' }
        ],
        borrowerName: [
          { required: true, message: '请输入借阅人姓名', trigger: 'blur' }
        ],
        borrowerDepartment: [
          { required: true, message: '请输入借阅人部门', trigger: 'blur' }
        ],
        borrowerPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        borrowReason: [
          { required: true, message: '请输入借阅原因', trigger: 'blur' }
        ],
        expectedReturnDate: [
          { required: true, message: '请选择预计归还日期', trigger: 'blur' }
        ]
      },
      searchFileNum: '',
      searchBorrower: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const data = {
            ...this.form,
            borrowDate: new Date().toISOString().slice(0, 19).replace('T', ' '),
            status: '待审批'
          };

          const config = {
            headers: {
              'Content-Type': 'application/json;charset=UTF-8'
            }
          };

          this.$http.post('/api/file_borrow_records/add', JSON.stringify(data), config)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success('借阅申请提交成功');
                this.dialogVisible = false;
                this.resetForm();
                this.getList();
              } else {
                this.$message.error(response.data.msg || '提交失败');
              }
            })
            .catch(error => {
              this.$message.error('提交失败：' + error.message);
            });
        }
      });
    },

    getList() {
      this.loading = true;
      this.$http.get('/api/file_borrow_records').then(response => {
        if (response.data.code === 200) {
          this.tableData = response.data.data;
        } else {
          this.$message.error(response.data.msg || '获取数据失败');
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    handleAdd() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.resetFields();
      });
    },

    resetForm() {
      this.$refs.form.resetFields();
    },

    getStatusType(status) {
      switch (status) {
        case '待审批':
          return 'warning';
        case '已通过':
          return 'success';
        case '已拒绝':
          return 'danger';
        default:
          return 'info';
      }
    },

    handleSearch() {
      this.loading = true;
      let searchPromise;

      if (this.searchFileNum) {
        searchPromise = this.$http.get(`/api/file_borrow_records/file/${this.searchFileNum}`);
      } else if (this.searchBorrower) {
        searchPromise = this.$http.get(`/api/file_borrow_records/borrower/${this.searchBorrower}`);
      } else {
        searchPromise = this.$http.get('/api/file_borrow_records');
      }

      searchPromise
        .then(response => {
          if (response.data.code === 200) {
            this.tableData = response.data.data || [];
          } else {
            this.tableData = [];
          }
        })
        .catch(() => {
          this.tableData = [];
        })
        .finally(() => {
          this.loading = false;
        });
    },

    handleDelete(recordId) {
      this.$confirm('确认删除该借阅记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`/api/file_borrow_records/delete/${recordId}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('删除成功');
              this.getList();
            } else {
              this.$message.error(response.data.msg || '删除失败');
            }
          })
          .catch(() => {
            this.$message.error('删除失败，请稍后重试');
          });
      });
    },

    handleStatusChange(recordId, newStatus) {
      this.$confirm(`确认将状态修改为"${newStatus}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = `/api/file_borrow_records/${recordId}/status?status=${encodeURIComponent(newStatus)}`;

        this.$http.put(url)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('状态修改成功');
              this.getList();
            } else {
              this.$message.error(response.data.msg || '修改失败');
              this.getList();
            }
          })
          .catch(error => {
            this.$message.error('修改失败：' + error.message);
            this.getList();
          });
      }).catch(() => {
        this.getList();
      });
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.el-table {
  margin-top: 15px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
